<?php

namespace Short\Controllers;


use Complex\Exception;

use Helpers\Main;
use Modules\ShortCut;
use Helpers\Template;
use Helpers\Assets;
use Helpers\UserPower;
use Services\ConfigManage;

class ManageController extends ControllerBase
{

    public function onConstruct()
    {
        parent::onConstruct();
        $this->userId = Main::getLoginUserInfo('userId');
        if (!$this->userId) {
            throw new \Exception('缺少用户id');
        }
    }


    private static $enums = [
        'public' => [0 => '全部', 2 => '非默认', 1 => '默认'],
    ];

    /**
     * 管理员快捷键列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ylf 20181107
     */
    public function indexAction()
    {
        UserPower::checkUserPower('Short_Manage') or die('权限不足');
        Assets::easyUI();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/myTool.js');
        $this->view->pick('manage/MsgList');
        Assets::importJs('js/noMsgList.js');
        Template::exists('MsgList', 'list') or die(Main::showMessageModal('MsgList.xml 配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $listSearchArr = [];
        $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
        $enums = self::$enums;
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_type', 'label' => ' 默认：',
            'data' => $enums['public'], 'default' => '');
        $model = new ShortCut();
        $sModel = $model->modelArr();
        $listSearchArr[] = ['type' => 'select', 'id' => 'model', 'label' => ' 模块：', 'data' => [0 => '--选择--'] + $sModel];
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 名称： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找',
            'icon' => 'fa-search', 'style' => 'margin-left:10px');
        $this->view->setVars(array(
            'Msg_List' => Template::createList('noticeMsgList', 'MsgList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
        ));
    }

    /**
     * 管理员分配权限页面
     *
     * @throws \Exception
     *
     * create by ylf 20181108
     * modify by fyh 20181210
     */
    public function addAction()
    {
        UserPower::checkUserPower('Short_Manage_Add') or die('权限不足');
        $iNoId = $this->request->getQuery('id', 'string');
        if ($iNoId) {
            if (!UserPower::checkUserPower('Msg_NoticeList_Edit')) {
                $checkStr = "parent.$('#bt_modal_confirm').hide();";
            } else {
                $checkStr = '';
            }
            try {
                $data = ConfigManage::manageAdd($iNoId);
                $notice = json_encode($data);
            } catch (Exception $e) {
                return $this->sendErrorResponse(500, $e->getMessage());
            }
        } else {
            $checkStr = '';
            $notice = '1';
        }
        Assets::easyUI();
        Assets::datetimePicker();
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/noticeForm.js');
        $this->view->pick('manage/addForm');
        $this->view->setVars([
            'notice' => $notice,
            'public' => self::$enums['public'],
            'check' => $checkStr,
            'dateTime' => date('Y年m月d日', time()),
            'data' => $data,
        ]);
    }
    /**
     *获取管理员快捷键列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     *
     * create by ylf 20181112
     * modify by fyh 20181210
     */
    public function getNoAfListAction()
    {

        $this->view->disable();
        $key = $this->request->getPost('key', 'string');
        $public = $this->request->getPost('type', 'string');
        $model = $this->request->getPost('model', 'string');
        if ($model == "--选择--") {
            $model = "";
        }
        try {
            $result = ConfigManage::manageGetNoAfList($key, $public, $model);
            return $this->sendJsonResponse($result);
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 管理员新增快捷键列表
     *
     * @throws \Exception
     *
     * create by ylf 20181112
     * modify by fyh 20181210
     */
    public function saveShortAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $data['iNoId'] = $this->request->getPost('iNoId', 'string');
        $data['name'] = $this->request->getPost('sName');
        $data['url'] = $this->request->getPost('vUrl');
        $data['openMode'] = $this->request->getPost('iopenMode');
        $data['module'] = $this->request->getPost('sModel');
        $data['public'] = $this->request->getPost('public');
        $data['tag'] = $this->request->getPost('sTag');
        $data['logo'] = $this->request->getPost('logo');
        if ($data['public'] == 1) {
            $data['public'] = true;
        } else {
            $data['public'] = false;
        }
        // 检查是否有文件上传
        if ($this->request->hasFiles() == true) {
            $files = $this->request->getUploadedFiles();
            if ($files[0]->getName()) {
                foreach ($files as $file) {
                   if (!$file->getName()) continue;
                    if (!$file->getRealType()) break;
                    $fileType = explode('/', $file->getRealType());
                    $fileType = $fileType[0];
                    if ($fileType != 'image') {
                        return $this->sendErrorResponse('400', '文件格式错误');
                    }
//                    die(Main::showMessageModal(109103015, '文件格式错误！'));
                    $fileName = $file->getName();
                    $fullPath = TEMP_PATH . $fileName;
                    if (!is_writable(TEMP_PATH)) {
                        return $this->sendErrorResponse('500', TEMP_PATH.'缓存无写入权限');
                    }
//                    die(Main::showMessageModal(109103016, '无写入权限！'));
                    $file->moveTo($fullPath);
                    $fullPath = Main::uploadToFileManageSystem($fullPath, 'qBankCover', 'XHSVADTKBSCECK');
                    @unlink($fullPath);
                    if ($fullPath) {
                        $data['logo'] = $fullPath;
                    };
                }
            }
        }
        try {
            $result = ConfigManage::manageSaveShort($data);
            return $result;
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 批量删除快捷键
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ylf 20181113
     * modify by fyh 20181210
     */
    public function delShortAction()
    {
        UserPower::checkUserPower('Short_Manage_Del') or die('权限不足');
        $sTag = $this->request->getPost('sTag', 'string');
        if (!is_array($sTag)) {
            $ids = explode(',', $sTag);
        } else {
            $ids = $sTag;
        }
        try {
            $result = ConfigManage::manageDelShort($ids);
            if ($result) {
                return $this->sendSuccessResponse('删除成功');
            } else {
                return $this->sendErrorResponse(400, '删除失败');
            }
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }


    /**
     * 个人设置快捷键列表
     * @throws \Exception
     *
     * modify by fyh 20181210
     */
    public function listAction()
    {
        Assets::easyUI();
        Assets::datetimePicker();
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/myTool.js');
        Assets::importJs('js/addShort.js');
        $this->view->pick('manage/userList');
        try {
            $result = ConfigManage::manageList();
            $this->view->setVars([
                'dataLists' => $result,
            ]);
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }


    public function notFoundAction()
    {
        return $this->response->setStatusCode(404)->setJsonContent(['code' => 404, 'error' => 'page not found!']);
    }


}

